package com.project.class4_6;

public class Test{
    public static void main(String[] args) {
        Access obj=new Access();
        new OneThread(obj);
        new TwoThread(obj);
    }
}

/**
 * 访问对象
 */
class Access{
    public  boolean isRun=true;
}
class OneThread  extends Thread{
    private Access obj;
    public OneThread(Access obj){
        this.obj=obj;
        new Thread(this).start();
    }
    public void  run() {
        int i=0;
        while (i<10) {
            synchronized(obj){
                if (obj.isRun==true){
                System.out.print("A");
                obj.isRun=false;
                obj.notify();
                i++;
                try {
                    Thread.sleep(300);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }else {
                    try {
                        obj.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
        }
    }
}}
class TwoThread extends Thread{
    private Access obj;
    public TwoThread(Access obj){
        this.obj=obj;
        new Thread(this).start();
    }
    public void  run() {
        int i=0;
        while (i<10) {
            synchronized (obj) {
                if (obj.isRun==false) {
                    System.out.print("B");
                    obj.isRun=true;
                    obj.notify();
                    i++;
                    try {
                        Thread.sleep(300);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }else {
                    try {
                        obj.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }
}